package com.birdboot.core;

import com.birdboot.http.HttpServletRequest;
import com.birdboot.http.HttpServletResponse;

import java.io.File;
import java.net.URISyntaxException;

public class DispatcherServlet {

    private static DispatcherServlet instance = new DispatcherServlet();
    private static File baseDir;
    private static File staticDir;
    static {
        try {
             baseDir = new File(
                    DispatcherServlet.class.getClassLoader().getResource(".").toURI()
            );
             staticDir = new File(baseDir,"static");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }
    private DispatcherServlet() {
    }

    public void service(HttpServletRequest request, HttpServletResponse response){
        String path = request.getUri();
        System.out.println("抽象路径："+path);
        File file = new File(staticDir,path);
        if (file.isFile()){
            response.setContentFile(file);
            response.addHeader("Server","BirdServer");

        }else{
            file = new File(staticDir,"404.html");
            response.setStatusCode(404);
            response.setStatusReason("NotFound");
            response.setContentFile(file);
            response.addHeader("Server","BirdServer");
        }
    }

    public static DispatcherServlet getInstance() {
        return instance;
    }
}
